package com.CMS.client.datasource;

import java.util.LinkedHashMap;
import java.util.List;

import com.CMS.client.ItemMenuService;
import com.CMS.client.ItemMenuServiceAsync;
import com.CMS.server.domain.ItemMenu;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class ItemMenuDataSource extends BaseDataSource{

	private SelectItem item;
	LinkedHashMap<String, String> valueMap = new LinkedHashMap<String, String>();
	DataSourceTextField fieldMenu = new DataSourceTextField("item","Item");
	private long idItem = 0;
	
	public ItemMenuDataSource(){
		super();
		item = new SelectItem();
		
		ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
		rpc.getItems(new AsyncCallback<List<ItemMenu>>() {
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onSuccess(List<ItemMenu> result) {				
				for(int i=0; i<result.size(); i++)
				{
					Long l = new Long(result.get(i).getId());
					valueMap.put(l.toString() , result.get(i).getDescription());
				}
					item.setValueMap(valueMap);
				//item.setOptionDataSource(new ItemMenuLookupDataSource());
			}
		});    
		item.addChangedHandler(new ChangedHandler() {
			
			@Override
			public void onChanged(ChangedEvent event) {
				idItem = new Long(event.getValue().toString());
			}
		});
		item.setValueField(getId());
		item.setAccessKey(getId());
		item.setDisplayField(getDescription());
		item.setEmptyPickListMessage(message.messageNoRecords());	    
	    fieldMenu.setEditorType(item);
	    addField(fieldMenu);
	    
	    GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
			  @Override 
			  public void onUncaughtException(Throwable e) {
			    GWT.log(e.getMessage(), e); 
			  }
			});
	}
	
	@Override
	protected void executeFetch(final String requestId, final DSRequest request,
			final DSResponse response) {
		
		ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
		rpc.getItems(new AsyncCallback<List<ItemMenu>>() {
			
			@Override
			public void onSuccess(List<ItemMenu> result) {
				final int startIndex = (request.getStartRow() < 0) ? 0 : request.getStartRow();
				final int endIndex = (request.getEndRow ()== null)? -1 : request.getEndRow();
				int size = result.size ();
                if (endIndex >= 0) {
                	if (endIndex < startIndex) {
                		size = 0;
                    }
                    else {
                        size = endIndex - startIndex + 1;
                    }
                }
                //Creamos los registros a devolver
				Record[] regs = new Record[result.size()];
				if (size > 0) {
					for (int i = 0; i < regs.length; i++) {
						Record record = new Record();
						copyValues(result.get(i), record);
						regs[i] = record;
					}
				}
				response.setData(regs);
				//IMPORTANTE: para que funcione el paginado debemos especificar
				//el total de registro del result set
				response.setTotalRows (result.size ());
				processResponse(requestId, response);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);			
			}
		});
		
	}

	@Override
	protected void executeAdd(final String requestId, DSRequest request,
			final DSResponse response) {
		
		ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
		final ListGridRecord rec = new ListGridRecord (request.getData());
		
		rpc.create(rec.getAttribute(getDescription()),
				   idItem, new AsyncCallback<Void>() {
			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}
			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub				
			}
		});
	}

	@Override
	protected void executeUpdate(final String requestId, DSRequest request,
			final DSResponse response) {
		
		ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
		Record old = request.getOldValues();
		final ListGridRecord rec = new ListGridRecord (request.getData());
		rpc.update((rec.getAttribute(this.getDescription()) == null) ? old.getAttribute(getDescription()) : rec.getAttribute(this.getDescription()),
					idItem,
					(rec.getAttributeAsBoolean(getFlagDelete()) == null) ? old.getAttributeAsBoolean(getFlagDelete()) : rec.getAttributeAsBoolean(getFlagDelete()),
					(rec.getAttributeAsInt(getId()) == null) ? old.getAttributeAsInt(getId()) : rec.getAttributeAsInt(getId()), 
					new AsyncCallback<Void>() {
						@Override
						public void onFailure(Throwable caught) {
							response.setStatus(RPCResponse.STATUS_FAILURE);
							processResponse(requestId, response);
						}
						@Override
						public void onSuccess(Void result) {
							// TODO Auto-generated method stub							
						}
					});
	}

	@Override
	protected void executeRemove(final String requestId, DSRequest request,
			final DSResponse response) {
		ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
		final ListGridRecord rec = new ListGridRecord (request.getData());
		rpc.delete(rec.getAttributeAsInt(getId()), new AsyncCallback<Void>() {
			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}
			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub				
			}
		});
	}
	
	private void copyValues(ItemMenu from, Record to) {
		to.setAttribute(getDescription(), from.getDescription());
		to.setAttribute(getId(), from.getId());
		to.setAttribute(getAddDate(), from.getAddDate());
		to.setAttribute(getModDate(), from.getModDate());
		to.setAttribute(getFlagDelete(), from.getFlagDelete());
		//item.setDefaultValues(Long.toString(from.getSubItem().get(0).getId()));
		//to.setAttribute("item", from.getSubItem().get(0).getDescription());
	}

}
